package com.search.controller;

import com.common.VO.SysResult;
import com.common.domain.Product;
import com.search.exception.MsgException;
import com.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Elias
 * @version 1.0
 * @date 2021-06-02 10:10
 * @description
 * @copyright 2021
 */
@RestController
@RequestMapping("/search")
public class SearchController {
  @Autowired private SearchService searchService;
  /**
   * 查询商品
   *
   * @param query 查询词
   * @param page 起始页
   * @param rows 查询条数
   * @return 商品列表
   */
  @RequestMapping("/manage/query")
  @ResponseBody
  public List<Product> searchProduct(
      @RequestParam("query") String query,
      @RequestParam(value = "page", defaultValue = "1") int page,
      @RequestParam(value = "rows", defaultValue = "30") int rows) {
    try {
      return searchService.searchProducts(query, page, rows);
    } catch (MsgException e) {
      return null;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  /**
   * 新增商品
   *
   * @param product 商品
   * @return vo
   */
  @RequestMapping("/manage/add")
  @ResponseBody
  public SysResult addProduct(@RequestBody Product product) {
    try {
      searchService.addProduct(product);
      return SysResult.ok();
    } catch (MsgException e) {
      return SysResult.build(201, e.getMessage(), e);
    } catch (Exception e) {
      return SysResult.build(500, e.getMessage(), e);
    }
  }
  /**
   * 删除商品
   *
   * @param product 商品
   * @return vo
   */
  @RequestMapping("/manage/delete")
  @ResponseBody
  public SysResult deleteProduct(@RequestBody Product product) {
    try {
      searchService.deleteProduct(product);
      return SysResult.ok();
    } catch (MsgException e) {
      return SysResult.build(201, e.getMessage(), e);
    } catch (Exception e) {
      return SysResult.build(500, e.getMessage(), e);
    }
  }
}
